<?php
/*************************************************************
*require_once("BackupMySQLData.class.php"); 
$link = @mysql_connect("localhost","数据库名","密码") or die ('Could not connect to server.'); 
mysql_query("use cms",$link); 
mysql_query("set names utf8",$link); 
$dbbck=new BackupMySQLData($link);//实例化它，只要一个链接标识就行了 
//备份数据时，如想备份一个数据库中的所有表，你可这样写： 
$dbbck->backupTables("cms","./",array('*')); 

//备份数据时，如想备份一个数据库中的仅一个表时，你可这样写： 
$dbbck->backupTables("cms","./",array('user')); 

//备份数据时，如想备份一个数据库中的多个表时，你可这样写： 

$dbbck->backupTables("cms","./",array('user','acl','informatoin')); 
//注解：$dbbck->backupTables("参1","参2",array());中， 
参1为：数据库名， 
参2为：要存放备份数据的位置（即目录地址） 
第三个为：你要保存那些表 
ok... 
*
**************************************************************/
class BackupMySQL
{
 private $mysql_link;
 private $dbName;
 private $dataDir;
 private $tableNames;
 public function __construct($mysql_link)
 {
  $this->mysql_link = $mysql_link;
 }

 public function backupTables($dbName, $dataDir, $tableNames)
 {
  $this->dbName = $dbName;
  $this->dataDir = $dataDir;
  $this->tableNames = $tableNames;
  $tables = $this->delarray($this->tableNames);
  $sqls = '';
  foreach($tables as $tablename)
  {
   if ($tablename == '')
   {
    continue;
   }

   $sqls .= "DROP TABLE IF EXISTS $tablename;\n";

   $rs = mysql_query("SHOW CREATE TABLE $tablename", $this->mysql_link);
   $row = mysql_fetch_row($rs);

   $sqls .= $row['1'] . ";\n\n";
   unset($rs);
   unset($row);

   $rs = mysql_query("select * from $tablename", $this->mysql_link);

   $field = mysql_num_fields($rs);
   while ($rows = mysql_fetch_row($rs))
   {
    $comma = '';
    $sqls .= "INSERT INTO `$tablename` VALUES(";
    for($i = 0;$i < $field;$i++)
    {
     $sqls .= $comma . "'" . $rows[$i] . "'";
     $comma = ',';
    }
    $sqls .= ");\n\n\n";
   }
  }
  $backfilepath = $this->dataDir . date("Ymdhis", time()) . '.sql';

  $filehandle = fopen($backfilepath, "w");
  fwrite($filehandle, $sqls);
  fclose($filehandle);
 }

 private function delarray($array)
 {
  foreach($array as $tables)
  {
   if ($tables == '*')
   {
    $newtables = mysql_list_tables($this->dbName, $this->mysql_link);
    $tableList = array();
    for ($i = 0; $i < mysql_numrows($newtables); $i++)
    {
     array_push($tableList, mysql_tablename($newtables, $i));
    }
    $tableList = $tableList;
   }
   else
   {
    $tableList = $array;
    break;
   }
  }
  return $tableList;
 }
}

?>